<template>
    <div class="detail-main" ref="gooddetailmain">
        <van-nav-bar title="标题" left-arrow class="header-title" style="background-color:#f8f8f8"
            @click-left="onClickLeft" @click-right="onClickRight">
            <template #left>
                <van-icon :name="newIcon4"  size="20"/>
            </template>
            <template #title>
                <span class="hometitle">{{detailtitle}}</span>
            </template>
            <template #right>
                <van-icon :name="newIcon3" :badge="shoppingcart" size="22"/>
            </template>
        </van-nav-bar>
        <div class="mgt"></div>
        <div class="banner-tab">
            <van-swipe :autoplay="99999999999999">
                <van-swipe-item v-for="(item,index) in DetailObj.picArr" :key="index" :style="{background:`url(${item})`}" class="details-x-swipe"></van-swipe-item>
            </van-swipe>

            <div class="share-black" v-if="needToShare">
                <div class="share-close-area" @click="needToShare=false"></div>
                <img src="../../assets/img/share-close.png" @click="needToShare=false" class="share-close" alt="">
                <img :src="DetailObj.is_like==0?love:loveActive" @click="setShoppingCart" class="share-love" alt="">
                <p>LIKE</p>
                <div class="share-line"></div>
                <div class="share-icon-group">
                    <img src="../../assets/img/share-pengyouquan.png" @click="sharetaol" alt="">
                    <img src="../../assets/img/share-wx.png" @click="sharetaol" alt="">
                    <img src="../../assets/img/share-webo.png" @click="sharetaol" alt="">
                    <img src="../../assets/img/share-qq.png" @click="sharetaol" alt="">
                </div>
            </div>
        </div>
        <!-- <hr class="banner-tab-hr"> -->
        <div class="good-details-info">
            <span class="details-title-1">{{DetailObj.brand}}</span>
            <span class="details-title-2">{{DetailObj.english_name}}</span>
            <span class="details-title-3">{{DetailObj.color}}</span>
            <span class="details-title-4">{{DetailObj.goods_name}}</span>
            <span class="details-title-5">{{DetailObj.goods_sn}}</span>
            <span class="details-pay-1">官方售价: 
                <span class="details-pay-1-item">
                    <img src="../../assets/img/payblack.png" class="details-pay-1-item-img" alt="">{{DetailObj.market_price}}
                </span>
            </span>
            <span class="details-pay-2">GO价: 
                <span class="details-pay-2-item">
                    <img src="../../assets/img/payred.png" alt="" />{{DetailObj.shop_price}}
                </span>
            </span>
        </div>

        <img class="details-redpay" src="../../assets/img/details-pay.png" alt="" @click="showdrawer" />
        <img class="callbackxxx" @click="jumptorule()" src="../../assets/img/indexback.png" alt="">
        
        <div class="offDefault" v-if="OutDetail">
            <van-nav-bar title="标题" left-arrow class="header-title"
            @click-left="onClickLeft">
            <template #left>
                <van-icon :name="newIcon4"  size="20"/>
            </template>
            <template #title>
                <span class="hometitle">HALF GO</span>
            </template>
        </van-nav-bar>
            <div class="Defaultbox">
                <img class="Defaultbox-img" src="../../assets/defaultpage/gooddetail-def.png" alt="">
            </div>
            <img class="defpagebtn" @click="onClickLeft" src="../../assets/defaultpage/gooddetail-btn.png" alt="">
        </div>

        <div>
            <a-drawer
                title=""
                id="detailDrawer"
                :height="drawerBodyheight"
                :placement="placement"
                :getContainer="getDetailMain"
                :destroyOnClose="true"
                :closable="false"
                @close="draweronClose"
                :visible="drawervisible">
                <div class="top-size">
                    <div class="top-size-title"></div>
                    <div class="top-size-title">
                        <span class="top-size-title-1">尺 <span class="letter-spacing"></span> 码</span>
                        <van-picker :columns="listData.map(item=>{return item.value})" @change="attrChange" :visible-item-count="3" item-height="30" :default-index="1"/>
                    </div>
                    <div class="top-size-title">
                        <span class="top-size-title-1">数 <span class="letter-spacing"></span> 量</span>
                        <van-picker :columns="listData2" @change="numChange" :visible-item-count="3" item-height="30" :default-index="1" />
                    </div>
                    <div class="top-size-title"></div>
                </div>
                <div class="botttom-pay-info" style="line-height:1.4;font-size: 0.1rem;">
                    <div class="coupon" @click="Jumptocoupon">
                        <span class="coupon-title">优惠券</span>
                        <span class="coupon-right">
                            <img class="coupon-img" src="../../assets/img/coupon.png" alt="">
                            <span class="coupon-canuse"><p>{{couponNum}}</p>张可用</span>
                            <img class="coupon-more" src="../../assets/img/more-coupon.png" alt="">
                        </span>
                    </div>
                    <div class="count-price">
                        <div class="order-price">
                            <span class="old-title">原价</span>
                            <span class="coupon-right">
                                <span style="font-size:0.3rem;">￥</span>
                                <span class="order-price-item-2">{{DetailObj.shop_price}}</span>
                            </span>
                        </div> 
                        <div class="order-price">
                            <span class="old-title">优惠折扣</span>
                            <span class="coupon-right">
                                <span class="price-less"></span>
                                <span style="font-size:0.3rem;">￥</span>
                                <span class="order-price-item-2">{{coupon.free_money?coupon.cate==1?coupon.free_money:`${coupon.free_rate}%`:'0.00'}}</span>
                            </span>
                        </div>
                        <div class="count">
                            <span class="count-title">合计</span>
                            <span class="count-right">
                                <span style="margin-right:8px;">￥</span>
                                <span>{{calcPrice()}}</span>
                            </span>
                        </div>
                    </div>
                    <div class="confirm-price">
                        <img src="../../assets/img/details-pay-btn.png" @click="JumpToOrder" alt="">
                    </div>
                </div>
            </a-drawer>
        </div>
    </div>
</template>
<script>
import {_ajaxdetail,_ajaxAttr,_confirmOrder} from '../../service/main.js'
import {_getjsapiticket} from '../../service/wxService.js'
import {_addCartGoods,_cartDel} from '../../service/shopcart.js'
import {_getUserCoupon} from '../../service/coupon'
import {_getCarNum} from '../../service/shopcart.js'
import {_getSharePic} from '../../service/main'
export default {
    data(){
        return{
            loveActive:require('../../assets/img/share-love.png'),
            love:require('../../assets/img/share-love-hol.png'),
            newIcon3: require('../../assets/img/gouwuche.png'),
			newIcon4: require('../../assets/img/backicon.png'),
            detailtitle:"",
            placement: 'bottom',
            drawervisible:false,
            listData: [],
            listData2: [0,1,2,3,4,5,6,7,8,9,10],
            attrs: "",
            num: 2,
            DetailObj:{},
            needToShare:false,
            drawerBodyheight:"55.73vh",
            OutDetail:false,

            goodAttr:0,
            goodNum:1,
            couponNum:0,
            shoppingcart:0,
            coupon:{
                free_money:0.00
            },
        }
    },
    activated(){
        
    },
    created(){
        // console.log(style)
        if(UsePhoneType==0){
            this.drawerBodyheight="55.73vh"
            document.styleSheets.forEach(item=>{
                item.insertRule(`
                @keyframes closeIn{
                    from{
                        opacity: 0;
                        bottom: 0;
                    }
                    to{
                        opacity: 1;
                        bottom: 55vh;
                    }
                }
            `)
            })
        }else{
            document.styleSheets.forEach(item=>{
                item.insertRule(`
                    @keyframes closeIn{
                        from{
                            opacity: 0;
                            bottom: 0;
                        }
                        to{
                            opacity: 1;
                            bottom: 55vh;
                        }
                    }
                `)
            })
        }
    },
    mounted(){
        console.log(this.$router)
        this.drawervisible=false
        this.needToShare=false
        let id = this.$route.query.id;
        this.getDetailsData(id)
        this.getUserShoppingCart()
        console.log(this.$route)
        

        if(localStorage.getItem("routerHistory")!=null&&localStorage.getItem("routerHistory")!=undefined){
            let url=localStorage.getItem("routerHistory")
            if(url.indexOf("/myCoupon")>-1){
                if(JSON.parse(localStorage.getItem("Coupon-Item"))!=undefined){
                    this.coupon=JSON.parse(localStorage.getItem("Coupon-Item"))
                }
                this.drawervisible=true
            }
        }
    },
    deactivated(){
        this.drawervisible=false
        this.DetailObj={}
        this.listData=[]
    },
    methods:{
        calcPrice(){
            if(this.coupon.cate){
                if(this.coupon.cate==1){
                    return ((Number(this.DetailObj.shop_price)*Number(this.goodNum))-Number(this.coupon.free_money)).toFixed(2)
                }else{
                    if(this.goodNum>1){
                        return ((Number(this.DetailObj.shop_price)*Number(this.goodNum))+(Number(this.DetailObj.shop_price)*Number(this.coupon.free_rate/100))).toFixed(2)
                    }else if(this.goodNum==1){
                        return (Number(this.DetailObj.shop_price)*Number(this.coupon.free_rate/100)).toFixed(2)
                    }
                }
            }else{
                return (Number(this.DetailObj.shop_price)*Number(this.goodNum)).toFixed(2)
            }
        },
        jumptorule(){
            this.$router.push({path:"/goodrule",query:{id:this.DetailObj.goods_id}})
        },
        async getUserShoppingCart(){
			let num=await _getCarNum()
			this.shoppingcart=num
		},
        attrChange(value, index){
            this.goodAttr=this.listData.filter(item=>{return item.value==index})[0].id
        },
        numChange(value, index){
            this.goodNum=index
        },
        JumpToOrder(){
            let Obj={}
            localStorage.removeItem("Coupon-Item")
            if(localStorage.getItem('user')==null||localStorage.getItem('user')==undefined){
                this.$router.push('/login')
				return
            }
            
            Obj.user_id=JSON.parse(localStorage.getItem("user")).user_id
            Obj.goods_id=this.DetailObj.goods_id
            Obj.goods_num=this.goodNum
            if(this.coupon.id){
                Obj.coupon_id=this.coupon.id
            }
            Obj.attr_id=this.goodAttr
            Obj.order_amount=this.calcPrice()

            // Obj.order_amount=Number(this.DetailObj.shop_price)*Number(this.goodNum)
            console.log(Obj)
            localStorage.setItem("OrderItem",JSON.stringify(Obj))
            this.$router.push('/order')
        },
        Jumptocoupon(){
            this.$router.push({path:'/myCoupon',query: {goodid:this.DetailObj.goods_id,amount:this.DetailObj.shop_price}})
        },
        getDetailMain(){
            return this.$refs.gooddetailmain
        },
        onClickLeft(){
            localStorage.removeItem("Coupon-Item")
            // this.$router.go(-1)
            this.$router.push("/indexs")
        },
        onClickRight(){
            if(!this.drawervisible){
                this.needToShare = !this.needToShare
            }
        },
        setShoppingCart(){
            let _this=this
            if(this.DetailObj.is_like==0){
                _addCartGoods(this.DetailObj.goods_id).then(res=>{
                    console.log(res)
                    if(res.errcode==1){
                        _this.$toast("商品已加入购物车")
                        _this.getDetailsData(_this.DetailObj.goods_id)
                    }
                })
            }else{
                if(this.DetailObj.cart_id!=""){
                    _cartDel(
                        this.DetailObj.cart_id
                    ).then(res=>{
                        console.log(res)
                        _this.$toast("商品已取消购物车")
                        _this.getDetailsData(_this.DetailObj.goods_id)
                    })
                }
            }
            
        },
        getDetailsData(id){
            let _this=this
            _ajaxdetail(id).then(res=>{
                if(res.errcode==0){
                    _this.OutDetail=true
                }
                res.data.picArr=[]
                res.data.picArr.push("http://"+res.data.left_img)
                res.data.picArr.push("http://"+res.data.right_img)
                res.data.picArr.push("http://"+res.data.front_img)
                res.data.picArr.push("http://"+res.data.behind_img)
                res.data.picArr.push("http://"+res.data.down_img)
                _this.DetailObj={}
                _this.DetailObj=res.data
                _this.DetailObj.is_like=res.is_like
                _this.DetailObj.cart_id=res.cart_id
                _this.detailtitle=res.data.brand
                _this.getMyCouponwithGood(id)
                _this.UpdateShareDate()
            })
            this.getAttr(id)
        },
        getMyCouponwithGood(id){
            let _this=this
            let uid=JSON.parse(localStorage.getItem("user")).user_id
            _getUserCoupon({
                user_id:uid,
                goods_id:id,
                order_amount:Number(this.DetailObj.shop_price)*Number(this.goodNum)
            }).then(res=>{
                // console.log(res)
                if(res.errcode==1){
                    _this.couponNum=res.data.filter(item=>{return item.is_use==1}).length
                }
            })
        },
        getAttr(id){
            let _this=this
            _ajaxAttr(id).then(res=>{
                _this.listData=[]
                if(res.data.length>0){
                    _this.goodAttr=res.data[0].attr_value[1].id
                    res.data[0].attr_value.forEach(item => {
                        _this.listData.push(item)
                    });
                    if(res.data[0].attr_value.length>1){
                        _this.attrs=res.data[0].attr_value[1].value
                    }
                }
            })
        },
        draweronClose(){
            this.drawervisible=false
        },
        showdrawer(){
            if(localStorage.getItem('user')||localStorage.getItem('user')!='undefined'){
                if(this.needToShare){
                    return
                }
                this.drawervisible=true
            }else{
                this.$router.push("/login")
            }
        },
        sharetaol(){
            this.$toast(`请使用右上角"..."分享`)
        },
        async ShareTopyq(){
            // let _this=this
            // let localhref=window.location.href
            // await _getjsapiticket(localhref).then(res=>{
            //     console.log("_getjsapiticket",res)
            //     if(res.errcode==1){
            //         localStorage.setItem("WXjsapi_ShareTopyq",JSON.stringify(res.data))
            //         wx.config({
            //             debug: true, 
            //             appId: res.data.appid, // 必填，公众号的唯一标识
            //             timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            //             nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            //             signature: res.data.signature,// 必填，签名，见附录1
            //             jsApiList: [
            //                 "onMenuShareTimeline"
            //             ]
            //         });
            //     }
            // })
            // let conf={
            //     title: _this.DetailObj.goods_name, // 分享标题
            //     link: localhref, // 分享链接
            //     imgUrl: _this.DetailObj.picArr[0], // 分享图标
            //     success: function () { 
            //         // 用户确认分享后执行的回调函数
            //         alert("shared Successed")
            //     },
            //     cancel: function () { 
            //         // 用户取消分享后执行的回调函数
            //         alert("shared cancel")
            //     }
            // }
            // await wx.ready(()=>{
            //     alert("ready")
            //     wx.onMenuShareTimeline(conf);
            // })
              
        },
        async UpdateShareDate(){
            let _this=this
            let localhref=window.location.href
            let conf1,conf2

            await _getSharePic({id:1}).then(res=>{
                conf1={ 
                    title: _this.DetailObj.brand, // 分享标题
                    desc: "更多折惠，极致享受，千款商品，邀您畅购......", // 分享描述
                    link: localhref, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: `http://www.starrymedia.vip${res.data.path}`, // 分享图标
                }
                conf2={ 
                    title: _this.DetailObj.brand, // 分享标题
                    link: localhref, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: `http://www.starrymedia.vip${res.data.path}`, // 分享图标
                }
            })


            await _getjsapiticket(localhref).then(res=>{
                console.log("_getjsapiticket",res)
                if(res.errcode==1){
                    // localStorage.setItem("WXjsapi_ticket",JSON.stringify(res.data))
                    wx.config({
                        debug: false, 
                        appId: res.data.appid, // 必填，公众号的唯一标识
                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                        signature: res.data.signature,// 必填，签名，见附录1
                        jsApiList: [
                            "updateAppMessageShareData","onMenuShareAppMessage",
                            "updateTimelineShareData","onMenuShareWeibo"
                        ]
                    });
                    setTimeout(()=>{
                        wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                            wx.updateAppMessageShareData(conf1)
                            wx.updateTimelineShareData(conf2)
                            wx.onMenuShareWeibo(conf1);
                        });
                        wx.error(function(res){
                            // alert(JSON.stringify(res))
                        });
                    },400)
                }
            })
            
            
        },
        async ShareTowx(){
            // let _this=this
            // let localhref=window.location.href
            // await _getjsapiticket(localhref).then(res=>{
            //     console.log("_getjsapiticket",res)
            //     if(res.errcode==1){
            //         localStorage.setItem("WXjsapi_ticket",JSON.stringify(res.data))
            //         wx.config({
            //             debug: true, 
            //             appId: res.data.appid, // 必填，公众号的唯一标识
            //             timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            //             nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            //             signature: res.data.signature,// 必填，签名，见附录1
            //             jsApiList: [
            //                 "onMenuShareAppMessage"
            //             ]
            //         });
            //     }
            // })

            // let conf={
            //         title: _this.DetailObj.goods_name, // 分享标题
            //         desc: 'ABCDEFG', // 分享描述
            //         link: localhref, // 分享链接
            //         imgUrl: _this.DetailObj.picArr[0], // 分享图标
            //         type: 'link', // 分享类型,music、video或link，不填默认为link
            //         dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            //         success: function () { 
            //             // 用户确认分享后执行的回调函数
            //             alert("shared Successed")
            //         },
            //         cancel: function () { 
            //             // 用户取消分享后执行的回调函数
            //             alert("shared cancel")
            //         }
            //     }

            // await wx.ready(()=>{
            //     wx.onMenuShareAppMessage(conf);
            // })
            
        },
        async ShareTowb(){
            // let _this=this
            // let localhref=window.location.href
            // await _getjsapiticket(localhref).then(res=>{
            //     console.log("_getjsapiticket",res)
            //     if(res.errcode==1){
            //         localStorage.setItem("WXjsapi_ticket",JSON.stringify(res.data))
            //         wx.config({
            //             debug: true, 
            //             appId: res.data.appid, // 必填，公众号的唯一标识
            //             timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            //             nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            //             signature: res.data.signature,// 必填，签名，见附录1
            //             jsApiList: [
            //                 "onMenuShareWeibo"
            //             ]
            //         });
            //     }
            // })
            // await wx.ready(()=>{
            //     wx.onMenuShareWeibo({
            //         title: _this.DetailObj.goods_name, // 分享标题
            //         desc: '测试测试测试', // 分享描述
            //         link: '', // 分享链接
            //         imgUrl: '', // 分享图标
            //         success: function () { 
            //             // 用户确认分享后执行的回调函数
            //         },
            //         cancel: function () { 
            //             // 用户取消分享后执行的回调函数
            //         }
            //     });
            // })
            
        },
        async ShareToqq(){


            // let _this=this
            // let localhref=window.location.href
            // await _getjsapiticket(localhref).then(res=>{
            //     console.log("_getjsapiticket",res)
            //     if(res.errcode==1){
            //         localStorage.setItem("WXjsapi_ticket",JSON.stringify(res.data))
            //         wx.config({
            //             debug: true, 
            //             appId: res.data.appid, // 必填，公众号的唯一标识
            //             timestamp: res.data.timestamp, // 必填，生成签名的时间戳
            //             nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            //             signature: res.data.signature,// 必填，签名，见附录1
            //             jsApiList: [
            //                 "onMenuShareQQ",
            //             ]
            //         });
            //     }
            // })
            // await wx.ready(()=>{
            //     wx.onMenuShareQQ({
            //         title: _this.DetailObj.goods_name, // 分享标题
            //         desc: '', // 分享描述
            //         link: '', // 分享链接
            //         imgUrl: '', // 分享图标
            //         success: function () { 
            //         // 用户确认分享后执行的回调函数
            //         },
            //         cancel: function () { 
            //         // 用户取消分享后执行的回调函数
            //         }
            //     });
            // })
            
        }
    }
}
</script> 
<style scoped>
@import url('details.css');
</style>
